package com.imooc.aspect;

import com.imooc.config.SellerConfig;
import com.imooc.constants.CookieConstant;
import com.imooc.constants.RedisConstant;
import com.imooc.exception.SellerAuthorizeException;
import com.imooc.utils.CookieUtil;
import com.imooc.utils.RedisUtil;
import com.imooc.utils.SellContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * FileName: SellerAuthorizeAspect.java
 * Description: 登录校验aop
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2021/1/4
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SellerConfig sellerConfig;

    @Pointcut("execution(public * com.imooc.controller.Seller*.*(..))" +
            "&& !execution(public * com.imooc.controller.SellerUserController.*(..))")
    public void verify() {}

    @Before("verify()")
    public void doVerify() {
        if (Boolean.FALSE.equals(sellerConfig.getAuthorize())) {
            return;
        }

        HttpServletRequest request = SellContextHelper.getRequest();
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie == null) {
            log.warn("【卖家端登录验证】Cookie中查不到token");
            throw new SellerAuthorizeException();
        }

        // 查redis
        String key = String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue());
        Object token = this.redisUtil.get(key);
        if (token == null) {
            log.warn("【卖家端登录验证】Redis查不到token, key={}", key);
            throw new SellerAuthorizeException();
        }

        // redis已经存在token缓存，表示登录了，放行
    }
}
